<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1">
		<title>Marketing Kit - Mobile</title>
		<link rel="stylesheet" href="css/themes/Bootstrap.css">
		<link rel="stylesheet" href="css/jquery.mobile.structure-1.4.0.min.css" />
		<link rel="stylesheet" href="css/jquery.mobile.icons.min.css" />
		<script src="js/jquery-1.8.2.min.js"></script>
		<script src="js/jquery.mobile-1.4.0.min.js"></script>
		<script type="text/javascript" src="cordova.js"></script>
		<script>
			//global variable
			var version = localStorage.getItem('ls_lastversion');
			var compName = localStorage.getItem('ls_compname');
			var updateStatus = localStorage.getItem('ls_update');
			var compId = localStorage.getItem('ls_compid');
			var sqlCatArr = new Array();
			var sqlVerArr = new Array();
			var db = null;	
			var jml = 0;		
			
			//database connection
			init();
				   		
			//load news
			getNews();
			
			$(document).ready(function(){
			
				//hide update first
				$('#btnUpdate').hide();
												
				$('#lableTitle').text(compName);
								
				$("#btnStart").click(function(){
					$.mobile.loading( 'show', {
						text: 'Loading to menu utama!',
						textVisible: true,
						theme: 'c',
						html: ""
					});
					var param = 'sub_id=2';
					window.location="menu_page.htm?"+param;
				});
								
				$("#btnExit").click(function(){
					if (confirm("Anda yakin ingin keluar?")){
					   navigator.app.exitApp();
					}
					
				});

				$("#btnPersonal").click(function(){
					$.mobile.loading( 'show', {
						text: 'Loading to Product!',
						textVisible: true,
						theme: 'c',
						html: ""
					});
					var param = 'sub_id=4';
					window.location="list_product_0.htm?"+param;
				});
				
				$('#btnUpdate').click(function(){
					$.mobile.loading('show', {
						text: 'Loading to update new version!',
						textVisible: true,
						theme: 'c',
						html: ''
					});
					updateVersion();
					getNews();
				});
										
			});
			
			function onBackKeyDown() {
				
				if (confirm("Anda yakin ingin keluar?")){
				   navigator.app.exitApp();
				}
				
			}
			
			function getParam( name ){
				name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
				var regexS = "[\\?&]"+name+"=([^&#]*)";  
				var regex = new RegExp( regexS );  
				var results = regex.exec( window.location.href ); 
				if( results == null )
					return "";  
				else
					return results[1];
			}
			
			function updateVersion(){
				
					db.transaction(
						function(tx){
							for(var j=0;j<sqlCatArr.length;j++){
								//alert(sqlCatArr[j]);
								tx.executeSql(sqlCatArr[j]);
							}							
						},
						function(err){
							alert('Insert New Data Error : '+err);
						},
						function(){
							alert('Update New Data Success');
						});
				
				
						
					db.transaction(
						function(tx){
							for(var j=0;j<sqlVerArr.length;j++){	
								//alert(sqlVerArr[j]);
								tx.executeSql(sqlVerArr[j]);
							}
						},
						function(err){
							alert('Insert Version Error : '+err);
						},
						function(){
							alert('Update Version Success');
							$.mobile.loading('hide');
							$('#btnUpdate').hide();
						});
				
			}
			
			function createSchema(tx){
				tx.executeSql('CREATE TABLE IF NOT EXISTS tb_news ( '+
	       				'news_id INTEGER PRIMARY KEY,'+
	       				'title VARCHAR(200),'+
	       				'description VARCHAR(65535),'+
	       				'newsdate DATETIME,'+
	       				'cat_id INTEGER,'+
	       				'comp_id INTEGER)');
	       				
	       		tx.executeSql('CREATE TABLE IF NOT EXISTS tb_data_version ('+ 
						'ver_id INTEGER PRIMARY KEY,'+
						'ver_name VARCHAR(200) ,'+
						'comp_id INTEGER)');
					
				tx.executeSql('CREATE TABLE IF NOT EXISTS tb_product ('+
						'prod_id INTEGER PRIMARY KEY,'+
						'name varchar(100),'+
						'category varchar(100),'+
						'cat_id INTEGER,'+
						'definition VARCHAR(65535),'+
						'advantage VARCHAR(65535),'+
						'syarat VARCHAR(65535),'+
						'waktu VARCHAR(65535),'+
						'tipe VARCHAR(65535),'+
						'catatan VARCHAR(65535))');
						
				tx.executeSql('CREATE TABLE IF NOT EXISTS tb_categories ( '+
						'cat_id INTEGER PRIMARY KEY,'+
						'sub_id INTEGER,'+
						'name VARCHAR(100),'+
						'icon VARCHAR(50),'+
						'comp_id INTEGER)');
								
				tx.executeSql('CREATE TABLE IF NOT EXISTS tb_calendar ( '+
						'cal_id INTEGER PRIMARY KEY,'+
						'dt_waktu DATETIME,'+
						'title VARCHAR(200),'+
						'message VARCHAR(65535),'+
						'comp_id INTEGER,'+
						'user_id INTEGER)');
			}
			
			function getPage(newsId){
				$.mobile.loading( 'show', {
						text: 'Loading to detil berita!',
						textVisible: true,
						theme: 'c',
						html: ""
					});
				var catName = 'Berita';
				var param='news_id='+newsId+'&cat_name='+catName;
				window.location="dtl_berita.htm?"+param;
			}
			
			function getNews(){
				db = window.openDatabase("marketkit", "1.0", "Market Kit Database", 1000000);
				db.transaction(
					function(tx){
						var sql = 'select * from tb_news where cat_id=3 order by datetime(newsdate) desc limit 3';
						//alert('sql news:'+sql);
						tx.executeSql(sql, [], function (tx, result){
							var index = 0;
							$('#listViewId').empty();
							$('.listViewId').append('<li data-role="list-divider">Berita Terbaru</li>');
							for(var j=0; j<result.rows.length;j++){
								var obj = result.rows.item(j);
								var strLiNews = '<li data-icon="arrow-r"><a href="#" onclick="getPage('+obj.news_id+')">'+obj.title+'</a></li>';
								$('.listViewId').append(strLiNews);
								index++;
							}
							
							if(index==0){
								$('.listViewId').append('<li><strong style="color:red">Tidak ada data.</strong></li>');
							}
							
							$('#listViewId').listview('refresh');
						});
					}, function(err){
						//alert('Err getNews sql:'+err);
						$('#listViewId').empty();
						$('.listViewId').append('<li data-role="list-divider">Berita Terbaru</li>');
						$('.listViewId').append('<li><strong style="color:red">Tidak ada data.</strong></li>');
						$('#listViewId').listview('refresh');
					}, function(){
					
					}
				);
			}
			
			function getErrorDb(err){
				alert('Error DB: '+err);
			}
			
			function getSuccess(){
				alert('Transaction Success');
			}
			
			function onDeviceReady(){
				try{
					db = window.openDatabase("marketkit", "1.0", "Market Kit Database", 1000000);
					db.transaction(createSchema, getErrorDb, function() {
						//alert('insert schema ok');
					});
										
					db.transaction(
						function(tx){
																												
							var sql = "select * from tb_data_version";														
							tx.executeSql(sql, [], function (tx, result){
									jml = result.rows.length;
								
									var url = 'http://www.mamatzone.com/mkit/ws/version_ws.php?function=getNewDataVersion&comp_id='+compId+'&last_update='+jml;
									//var url = 'http://10.0.2.2/mkit/ws/version_ws.php?function=getNewDataVersion&comp_id='+compId+'&last_update='+jml;
									//alert('URL : '+url);
															
									$.getJSON(url,
										function(data){
											//alert('data : '+data.length);	
																				
											for(var i=0; i< data.length; i++){
												var obj = data[i];
												var sqlCat = obj.ver_transaction;
												var verId = obj.ver_id;
												var verName = obj.ver_name;
												sqlCatArr[i]=sqlCat;
												var sqlVer = 'INSERT INTO tb_data_version (ver_id,ver_name,comp_id ) VALUES ('+verId+',\''+verName+'\','+compId+')';
												sqlVerArr[i]=sqlVer;
												
											}
											
											if(data.length>0){
												$('#btnUpdate').show();
											}
											
											$('#txtLoading').hide();
										}
									);
									
									
							});
						}, getErrorDb, 
						
						function(){
							//alert('query get version ok');
						});
					
							
											
				}catch(e){
					alert("error:"+e);
				}
			}
			
			function init(){
	   			document.addEventListener("deviceready",onDeviceReady, false);
	   			document.addEventListener("backbutton", onBackKeyDown, false);
	   		}
	   		
		</script>
	</head>
	<body>
		<div data-role="page" data-theme="c">
			<div data-role="header" data-position="inline">
				<h1 id="lableTitle">Marketing Kit - Mobile</h1>
			</div>
			<div data-role="content" data-theme="a">
				<ul id="listViewId" class="listViewId" data-role="listview" data-inset="true" data-divider-theme="c">
					<li data-role="list-divider">Berita Terbaru</li>	
				</ul>
				<div data-role="fieldcontain" >
					<div id="txtLoading" align="center">Loading check Data Version...!</div>
					<a data-role="button" name="btnUpdate" id="btnUpdate" data-theme="c" data-icon="arrow-d">Update New Version</a>	
					
					<a data-role="button" name="btnPersonal" id="btnPersonal" data-theme="c" data-icon="user">Personal</a>
					<a data-role="button" name="btnCorporate" id="btnCorporate" data-theme="c" data-icon="gear">Corporate</a>
					<a data-role="button" name="btnStart" id="btnStart" data-theme="c" data-icon="navigation">Start</a>
					<a data-role="button" name="btnExit" id="btnExit" data-icon="delete" data-theme="c">Exit</a>			
				</div>
				
			</div>
		</div>
		
	</body>
</html>